import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch } from "../../components/RootProvider";
import "./login.css";
import { writeAuth } from "../../api/common";

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { login } = useDispatch();

  const from = location.state?.from?.pathname || "/";

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();

    const formData = new FormData(event.currentTarget);
    const username = formData.get("username") as string;
    const password = formData.get("password") as string;
    const save = formData.get("save") as string;

    if (!username || !password) {
      alert("用户名和密码不能为空");
      return;
    }
    const res = await login(username, password);
    if (res) {
      // 保存用户信息
      writeAuth(username, password, save === "true");

      // Send them back to the page they tried to visit when they were
      // redirected to the login page. Use { replace: true } so we don't create
      // another entry in the history stack for the login page.  This means that
      // when they get to the protected page and click the back button, they
      // won't end up back on the login page, which is also really nice for the
      // user experience.
      navigate(from, { replace: true });
    } else {
      alert("登录失败");
    }
  }

  return (
    <div className="login-page">
      <p>您必须登录才能在查看页面 {from}</p>

      <form onSubmit={handleSubmit}>
        <label>
          用户名: <input name="username" type="text" />
        </label>
        <br />
        <label>
          密码: <input name="password" type="password" />
        </label>
        <br />
        <label>
          保存登录信息:{" "}
          <input name="save" type="checkbox" defaultChecked value="true" />
        </label>
        <br />
        <button type="submit">登录</button>
      </form>
    </div>
  );
};

export { LoginPage };
